﻿using NetCore.Dtos;
using NetCore.Extensions;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace NetCore.Mail
{
    /// <summary>
    /// 邮件服务类
    /// </summary>
    public class MailService
    {
        private MailMessage _mailObj;
        private static SmtpClient _smtp = null;
        public MailService(MailDto model)
        {
            _mailObj = new MailMessage { From = new MailAddress(model.From) };
            _mailObj.To.Add(model.To);
            _mailObj.CC.Add(model.Cc);
            _mailObj.Subject = model.Subject;
            _mailObj.Body = model.Body;
            AddAttachments(model.AttachmentPaths);

            if (_smtp == null)
            {
                _smtp = new SmtpClient
                {
                    EnableSsl = true,//加密
                    Port = model.Port,
                    Host = model.Host
                };
            }

            //_smtp.UseDefaultCredentials = true;
            _smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            _smtp.Credentials = new NetworkCredential(model.UserName, model.License);
        }

        private void AddAttachments(List<string> paths)
        {
            if (paths != null)
            {
                foreach (var path in paths)
                {
                    AddAttachment(path);
                }
            }
        }

        private void AddAttachment(string path)
        {
            //建立邮件附件类的一个对象，语法格式为System.Net.Mail.Attachment(文件名，文件格式)
            var myAttachment = new Attachment(path, MediaTypeNames.Application.Octet);
            //MIME协议下的一个对象，用以设置附件的创建时间，修改时间以及读取时间
            var disposition = myAttachment.ContentDisposition;
            disposition.CreationDate = File.GetCreationTime(path);
            disposition.ModificationDate = File.GetLastWriteTime(path);
            disposition.ReadDate = File.GetLastAccessTime(path);
            _mailObj.Attachments.Add(myAttachment);
        }
        /// <summary>
        /// Send Mail
        /// </summary>
        /// <param name="model">包含发件人、收件人、抄送人、主题、附件地址的对象</param>
        public async Task SendAsync(MailDto model)
        {
            _mailObj.From = new MailAddress(model.From);
            _mailObj.To.Clear();
            _mailObj.To.Add(model.To);
            _mailObj.CC.Clear();
            if (model.Cc.HasValue())
            {
                _mailObj.CC.Add(model.Cc);
            }
            _mailObj.Subject = model.Subject;
            _mailObj.Body = model.Body;
            _mailObj.IsBodyHtml = false;//todo：待扩展：邮件添加隐藏a标签，连接到网站某action里更新邮件发送与读取状态
            _mailObj.BodyEncoding = Encoding.UTF8;
            _mailObj.Priority = MailPriority.High;
            _mailObj.Attachments.Clear();
            //邮件附件
            foreach (var path in model.AttachmentPaths)
            {
                AddAttachment(path);
            }
            
            //smtp 发送
            //_smtp.Send(_mailObj);
            _smtp.SendAsync(_mailObj, null);
        }
        /// <summary>
        /// Default Sent
        /// </summary>
        public async Task SendAsync()
        {
            //_smtp.Send(_mailObj);
            _smtp.SendAsync(_mailObj, new { Msg = "发送邮件..." });
        }

    }
}